<script lang='ts' setup>
import type { UserInfo } from '@/type';
import type { FormInstance, FormRules } from 'element-plus';
import { onMounted, reactive, ref } from 'vue';
import SlideVerify, { type SlideVerifyInstance } from "vue3-slide-verify";
import "vue3-slide-verify/dist/style.css";
import verifyImg1 from '@/assets/images/verify/壁纸1.jpg'
import verifyImg2 from '@/assets/images/verify/壁纸2.jpg'
import verifyImg3 from '@/assets/images/verify/黄科1.jpg'
import verifyImg4 from '@/assets/images/verify/黄科2.jpg'
import verifyImg5 from '@/assets/images/verify/黄科4.jpg'
import verifyImg6 from '@/assets/images/verify/黄科5.jpg'
import { doGet } from '@/assets/工具/网络请求';
import { USER } from '@/assets/工具/枚举';
import { useStore } from '@/stores/store';
import router from '@/router';
const userInfo = ref<UserInfo>({/* 登录信息 */
    // userName: '',
    // password: '',
    // identity: '',
    // phone: ''
} as UserInfo)
const store = useStore()
const formEl = ref<FormInstance>()   /* form表单的整个dom结构 */
const resetForm = (formEl: FormInstance | undefined) => {/* 重置表单内容和提示语 */
    if (!formEl) return
    formEl.resetFields()
}




const imageUrls = ref<string[]>([]);
type ImageModule = {
  default: string;
};

onMounted(async () => {
  // 使用 import.meta.glob 批量导入指定目录下的所有图片文件
  const imageModules = import.meta.glob<ImageModule>('@/assets/verify1/*.{png,jpg,jpeg,gif}');
  const urls: string[] = [];

  // 遍历导入的图片模块
  for (const path in imageModules) {
    const module: ImageModule = await imageModules[path]();
    // 将图片的 URL 添加到数组中
    urls.push(module.default);

  }

  imageUrls.value = urls;

});
const formRules = reactive<FormRules<UserInfo>>({
    userName: [
        {
            required: true,
            message: '账号不可为空',
            trigger: 'blur'
        }
    ],
    password: [
        {
            required: true,
            message: '密码不可为空',
            trigger: 'change'
        }
    ]
})
const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            console.log('登录信息校验成功');
            /*
                弹出拼图验证码，验证通过后才发送请求登录。
            */
            showVerify.value = true
            isLoading.value = true

        } else {
            console.log('登录信息校验失败', fields);
        }
    })
}
const msg = ref('');
const block = ref<SlideVerifyInstance>();

const onAgain = () => {
    msg.value = "检测到非人为操作的哦！ try again";
    // 刷新
    block.value?.refresh();
};

const onSuccess = async (times: number) => {
    msg.value = `验证通过, 耗时${(times / 1000).toFixed(1)}s`;
    showVerify.value = false
    /*
        发送网络请求
    */
    try {
        const response = await doGet(USER.USER_INFO, {
            params: {
                userName: userInfo.value.userName,
                password: userInfo.value.password
            }
        })
        isLoading.value = false
        if (response.data.length < 1) {
            loginError.value = '账号密码不匹配'
            showFaildAlert.value = true

        } else {
            // 登录成功
            showSuccessAlert.value = true
            store.token = response.data[0] //保存登录状态
            router.push({name:'home'})  //跳转到首页
        }
    } catch (error) {
        loginError.value = '网络异常，登录失败'
        showFaildAlert.value = true
        console.log('登录失败', error);
    }
    setTimeout(() => {
        showSuccessAlert.value = false
        showFaildAlert.value = false
    }, 3000);
};

const onFail = () => {
    msg.value = "验证不通过";
};

const onRefresh = () => {
    msg.value = "点击了刷新小图标";
};
const text = "向右滑动->"
const loginError = ref('')
const accuracy = 9
const showVerify = ref(false)/* 是否显示拼图验证码 */
const isLoading = ref(false)/* 是否展示加载中的遮罩层 */
/* eslint-disable @typescript-eslint/no-unused-vars */


const verifyImgs = [
    verifyImg1,
    verifyImg2,
    verifyImg3,
    verifyImg4,
    verifyImg5,
    verifyImg6
]
/* eslint-enable @typescript-eslint/no-unused-vars */
const showSuccessAlert = ref(false)
const showFaildAlert = ref(false)
const closeAlert = () => {
    showSuccessAlert.value = false
    showFaildAlert.value = false
}
</script>
<template>
    <div id="页面">
        <h1>
            小谦图书馆借阅管理系统
        </h1>
        <el-form ref="formEl" :rules="formRules" id="登录窗口" :model="userInfo" v-loading="isLoading">
            <div id="表单内容">
                <el-form-item label="账号" prop="userName">
                    <el-input v-model="userInfo.userName" clearable></el-input>
                </el-form-item>
                <el-form-item label="密码" prop="password">
                    <el-input v-model="userInfo.password" show-password type="password"></el-input>
                </el-form-item>
                <div id="按钮行">
                    <el-button type="info" @click="resetForm(formEl)">重置</el-button>
                    <el-button type="primary" @click="$router.push('/register')">注册</el-button>
                    <el-button @click="submitForm(formEl)" type="success">登录</el-button>
                </div>
            </div>
        </el-form>
        <div v-if="showVerify" id="验证码容器">
            <slide-verify ref="block" :imgs="imageUrls" :slider-text="text" :accuracy="accuracy" @again="onAgain"
                @success="onSuccess" @fail="onFail" @refresh="onRefresh"></slide-verify>
            <div>{{ msg }}</div>
        </div>
        <div id="提示框" v-if="showSuccessAlert || showFaildAlert">
            <el-alert title="登录成功" type="success" center show-icon @close="closeAlert" v-if="showSuccessAlert" />
            <el-alert :title="loginError" type="error" center show-icon @close="closeAlert" v-if="showFaildAlert" />
        </div>
    </div>
</template>
<style scoped>
#提示框 {
    width: 300px;
    position: fixed;
    left: calc(50% - 150px)
}

#验证码容器 {
    position: fixed;
    left: calc(50% - 155px);
    top: 50px;
}

#按钮行 {
    display: flex;
    justify-content: space-between;
    width: 200px;
    margin: auto;
}

#表单内容 {
    width: 300px;
    margin: auto;
    box-sizing: border-box;
    padding-top: 110px;
}

#登录窗口 {
    width: 500px;
    height: 300px;
    background-color: #fff;
    position: fixed;
    left: calc(50% - 250px);
    bottom: calc(50% - 150px);
    border-radius: 20px;
}

h1 {
    text-align: center;
    font-size: 36px;
    color: #377bc0;
    margin: 0;
    padding-top: 60px;
}

#页面 {
    background-image: url(@/assets/images/index/图书馆.jpg);
    background-size: 100% 100%;
    height: 100%;
}
</style>
